package cn.alise.interceptor;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import cn.alise.consts.BaseConsts;
import cn.alise.enums.EnumClass;
import cn.alise.exception.AuthorizationException;
import cn.alise.qdp.model.log.UserAccessLogs;
import cn.alise.qdp.model.user.User;
import cn.alise.qdp.service.log.UserAccessLogsService;

/**
 * 统一异常处理
 * @author 陈昊
 *
 */
@Component
@ControllerAdvice
public class GlobalExceptionHandler {
	
	protected Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private UserAccessLogsService userAccessLogsService;

	@ExceptionHandler(value = Exception.class)
	public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception ex) throws Exception {
		
		Map<String, Object> model = new HashMap<String, Object>();  
        model.put("ex", ex.getCause());  
        
        // session中获取人员信息
 		HttpSession session = request.getSession();
 		User user = (User) session.getAttribute(BaseConsts.IUser.USER_SESSION_KEY);
 		
 		// 请求的URL
 		String url = request.getRequestURI();
 		
 		if (user!=null) {
 			// 保存异常日志
 	 		UserAccessLogs userAccessLogs = new UserAccessLogs();
 	 		userAccessLogs.setUserId(user.getUserId());
 	 		userAccessLogs.setUserName(user.getUserName());
 	 		userAccessLogs.setAccount(user.getAccount());
 	 		userAccessLogs.setRoleName(user.getRoleNameArr());
 	 		userAccessLogs.setIpaddress(getIpAddress(request));
 	 		userAccessLogs.setType(EnumClass.LogOperation.EXCEPTION.getKey());
 	 		userAccessLogs.setRemark("异常！ " + ex);
 	 		userAccessLogs.setPath(url);
 	 		
 	 		userAccessLogs.setCreatedTime(new Timestamp(System.currentTimeMillis()));
 	 		this.userAccessLogsService.save(userAccessLogs);
 		}
		
		// 根据不同错误转向不同页面  
 		System.out.println(ex);
    	logger.error(ex);
        if (ex instanceof AuthorizationException) {
            return new ModelAndView("pages/login/login", model);  
        } else {  
            return new ModelAndView("error/error", model);  
        }
	}
	
	/**
	 * 获取ip地址
	 */
	public static String getIpAddress(HttpServletRequest request) { 
	    String ip = request.getHeader("x-forwarded-for"); 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("WL-Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("HTTP_CLIENT_IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getRemoteAddr(); 
	    } 
	    return ip; 
	  }
}
